package org.onion.pattern.event.springboot.rocketmq.consume.distribute;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.onion.pattern.event.springboot.rocketmq.annotation.RocketMQEventListener;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.EventListenerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotatedElementUtils;

import java.lang.reflect.Method;

@Slf4j
public class RocketEventListenerFactory implements EventListenerFactory, Ordered , ApplicationContextAware {

    /**
     * 越小越在前
     */
    @Setter
    @Getter
    private int order = 30;
    private ApplicationContext applicationContext;

    @Override
    public boolean supportsMethod(Method method) {
        return AnnotatedElementUtils.hasAnnotation(method, RocketMQEventListener.class);
    }

    @Override
    public ApplicationListener<?> createApplicationListener(String beanName, Class<?> type, Method method) {
        return new RocketMQListenerMethodAdapter(beanName, type, method,applicationContext);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}
